﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Dict.DataModel;
using Dict.Blo;
using UI;
using Room;
public class GuideManager:MonoBehaviour
{

    #region Instance
    static private GuideManager instance;
    static public GuideManager Instance
    {
        get
        {
            return instance;
        }
    }
    void Awake()
    {
        instance = this;
        
    }
    #endregion

    public GuideMask guideMask;

    public int curStepIdx;
    private TableGuideStep curStep;
    private string curGuideId = "";
    public string testGuideId = "";

    private bool running;

    private string waitingStepId=null;

    void Start()
    {
        
    }

    void OnEnable()
    {
        if (!string.IsNullOrEmpty(testGuideId))
        {
            StaticData.playerData.currentGuideId = testGuideId;
            curGuideId = StaticData.playerData.currentGuideId;
            OnLogin(true);
            if(!running)
            {
                OnLevelUp();
            }
        }
    }

    private void GuideStart(string guideId,string tag)
    {
        if(CheckGuideCanStart(guideId))
        {

        }
        else
        {
            return;
        }

        curGuideId = guideId;
        curStep = null ;
        curStepIdx = -1;

        var curGuideSteps = Dict.DictDataManager.Instance.tableGuideStepDao.GetByOneIndex(curGuideId);
        for(int i=0;i<curGuideSteps.Count;i++)
        {
            if(curGuideSteps[i].tag.Equals(tag))
            {
                curStepIdx = i - 1;
                break;
            }
        }
        running = true;
        StopAllCoroutines();
        StartCoroutine(WaitForStoryEnd());
    }

    private IEnumerator WaitForStoryEnd()
    {
        while(ManagerController.Instance.storyManager.isRunning())
        {
            yield return null;
        }
        NextStep();
    }
    
    private void NextStep(int offset=1)
    {
        
        var curGuideSteps = Dict.DictDataManager.Instance.tableGuideStepDao.GetByOneIndex(curGuideId);

        curStepIdx+= offset;
        if (curStepIdx >= curGuideSteps.Count)
        {
            OnGuideEnd();
            return;
        }
        curStep = curGuideSteps[curStepIdx];
        Debug.Log("####[GuideMessage]NextStep:" + curStep.stepId + ";" + curStep.guideId + ";" + curStep.type+";"+curStep.path+";"+curStep.param);
        switch (curStep.type)
        {
            case "Click":
                StepClick();
                break;
            case "PathFinding":
                StepPathFinding();
                break;
            case "ClickEquip":
                StepClickEquip();
                break;
            case "Return":
                StepReturn();
                break;
            case "ClickAny":
                StepClickAny();
                break;
            case "GuideMove":
                StepGuideMove();
                break;
            case "GuideLookMonster":
                StepGuideLookMonster();
                break;
            case "ClickNPC":
                StepClickNPC();
                break;
            case "WaitObject":
                StepWaitObject();
                break;
            case "WaitArenaPage":
                StepWaitArenaPage();
                break;
            case "WaitRecruit":
                StepWaitRecruit();
                break;
            case "FindPlunderItem":
                StepFindPlunderItem();
                break;
            case "Jump":
                StepJump();
                break;
            case "Wait":
                StepWait();
                break;
            case "WaitSelfCreated":
                StepWaitSelfCreated();
                break;
            case "Transfer":
                StepTransfer();
                break;
            case "GuideFish":
                StepGuideFish();
                break;
            case "Move":
                StepMove();
                break;
            case "GuideMine":
                StepGuideMine();
                break;
            case "RotateHero":
                StepRotateHero();
                break;
            case "ShowWindow":
                SetShowWindowState();
                break;
            default:
                NextStep();
                break;
        }
        //guideMask.ShowForceWithWord()
    }

    #region Steps

    #region Click 
    private string lastDelegateMethodName;
    private List<EventDelegate> lastEventDelegates;
    private void StepClick()
    {
        guideMask.ShowForceWithWord(null,
            curStep.text,
            new Vector3((float)curStep.posX, (float)curStep.posY, 0),
            (GuideMask.DialogType.NONE), (GuideMask.HandType.NONE));
        StopAllCoroutines();
        StartCoroutine(_StepClick());
    }
    private IEnumerator _StepClick()
    {
        GameObject btnObject=null;
        while(btnObject==null||btnObject.activeInHierarchy==false)
        {
            btnObject = GameObject.Find(curStep.path);
            yield return null;
        }

        lastEventDelegates = GetEventDelegatesOfObj(btnObject);
        RemoveGuideDelegate(lastEventDelegates);
        if (!string.IsNullOrEmpty(curStep.param))
        {
            lastDelegateMethodName = lastEventDelegates[0].methodName;
            lastEventDelegates[0].methodName = curStep.param;
        }

        var eventDelegate = new EventDelegate(this, "StepClickEnd");
        eventDelegate.oneShot = true;

        lastEventDelegates.Add(eventDelegate);

        waitingStepId = curStep.stepId;

        guideMask.ShowForceWithWord(btnObject,
            curStep.text,
            new Vector3((float)curStep.posX, (float)curStep.posY, 0),
            (GuideMask.DialogType)curStep.dialogType, (GuideMask.HandType)curStep.hand);

    }
    private void StepClickEnd()
    {
        if(curStep.stepId.Equals(waitingStepId))
        {
            waitingStepId = "";
        }
        else
        {
            //Debug.LogError("#####[GuideMessage]Double Clicked ######");
            return;
        }

        if (!string.IsNullOrEmpty(lastDelegateMethodName))
        {
            lastEventDelegates[0].methodName = lastDelegateMethodName;
            lastDelegateMethodName = null;
        }
        lastEventDelegates = null;

        NextStep();
    }
    #endregion
    #region PathFinding
    private void StepPathFinding()
    {
        //Room.RoomCharactor self = null;
        //self = Room.RoomManager.currentRoom.charactorManager.GetSelfCharactor();
        //self.transform.position = new Vector3(-6, 0, -6.25f);
        guideMask.ShowForceWithWord(null, "", Vector3.zero, 0, 0);
        guideMask.ActiveGray(false);
        StopAllCoroutines();
        StartCoroutine(_StepPathFinding(curStep.param));
    }
    private IEnumerator _StepPathFinding(string targetId)
    {
        while (true)
        {
            var self = RoomManager.currentRoom.charactorManager.GetSelfCharactor();
            var target = RoomManager.currentRoom.charactorManager.GetCharactor(targetId);
            if(self==null||target==null)
            {
                yield return null;
            }
            var selfAI = self.ai as RCAISelf;
            var distance = (target.transform.position - self.transform.position).magnitude;
            bool arrived = false;
            switch (target.type)
            {
                case CharactorType.StoryNPC:
                case CharactorType.NormalNPC:
                    if (distance <= target.ui.ClickRange)
                    {
                        arrived = true;
                    }
                    break;
                case CharactorType.Area:
                    if (distance < (target.ai as RCAIArea).areaRange)
                    {
                        arrived = true;
                    }
                    break;
            }
            if (arrived)
            {
                NextStep();
                yield break;
            }
            else
            {
                if (!selfAI.AutoPathFinding)
                    selfAI.GoToAndClick(target);
            }
            yield return null;
        }
    }
    #endregion
    #region ClickEquip
    EquipIcon.ClickCallBack tmpEquipIconCallBack;
    private void StepClickEquip()
    {
        guideMask.ShowForceWithWord(null,
            curStep.text,
            new Vector3((float)curStep.posX, (float)curStep.posY, 0),
            (GuideMask.DialogType.NONE), (GuideMask.HandType.NONE));
        StopAllCoroutines();
        StartCoroutine(_StepClickEquip());
    }
    private IEnumerator _StepClickEquip()
    {
        GameObject btnObject = null;
        while (btnObject == null||btnObject.activeInHierarchy == false)
        {
            yield return null;
            btnObject = GameObject.Find(curStep.path);
        }

        var equipIcon = btnObject.GetComponent<EquipIcon>();
        tmpEquipIconCallBack = equipIcon.GetChosedCallback();
        equipIcon.SetChosedCallback(StepClickEquipEnd);


        guideMask.ShowForceWithWord(btnObject,
            curStep.text,
            new Vector3((float)curStep.posX, (float)curStep.posY, 0),
            (GuideMask.DialogType)curStep.dialogType, (GuideMask.HandType)curStep.hand);

        waitingStepId = curStep.stepId;
    }
    private void StepClickEquipEnd(EquipIcon obj)
    {
        if(curStep.stepId.Equals(waitingStepId))
        {
            waitingStepId = "";
        }
        else
        {
            return;
        }
        tmpEquipIconCallBack(obj);

        obj.SetChosedCallback(tmpEquipIconCallBack);
        tmpEquipIconCallBack = null;

        NextStep();
    }
    #endregion
    #region Return
    private void StepReturn()
    {
        while(!PageManager.instance.currentPage.name.Equals("TownPage"))
        {
            PageManager.instance.currentPage.Close();
        }
        NextStep();
    }
    #endregion
    #region ClickAny
    private bool lastEasyTouchState = false;
    private void StepClickAny()
    {
        guideMask.ShowForceWithWord(null,
            curStep.text,
            new Vector3((float)curStep.posX, (float)curStep.posY, 0),
            (GuideMask.DialogType)curStep.dialogType, (GuideMask.HandType)curStep.hand);
        guideMask.onClickCallback = StepClickAnyEnd;

        lastEasyTouchState = EasyTouchTool.Instance.Enable;
        EasyTouchTool.Instance.Hide();

        waitingStepId = curStep.stepId;
    }
    private void StepClickAnyEnd()
    {
        if (curStep.stepId.Equals(waitingStepId))
        {
            waitingStepId = "";
        }
        else
        {
            return;
        }

        Debug.Log("####[GuideMessge]StepClickAnyEnd####");
        guideMask.onClickCallback = null;

        if(lastEasyTouchState)
            EasyTouchTool.Instance.ShowJoystick();
        NextStep();
    }
    #endregion
    #region GuideMove
    private bool waitingMove = false;
    private void StepGuideMove()
    {
        guideMask.ShowForceWithWord(null,
            curStep.text,
            new Vector3((float)curStep.posX, (float)curStep.posY, 0),
            (GuideMask.DialogType)curStep.dialogType, (GuideMask.HandType)curStep.hand);
        guideMask.ActiveMask(false);
        guideMask.ActiveGray(false);

        StopAllCoroutines();
        StartCoroutine(_StepGuideMove());
    }
    private IEnumerator _StepGuideMove()
    {
        Room.RoomCharactor areaArrow = null;
        Room.RoomCharactor areaFar = null;
        while (areaArrow == null|| areaFar==null)
        {
            yield return null;
            areaArrow = Room.RoomManager.currentRoom.charactorManager.GetCharactor("area_3");
            areaFar = Room.RoomManager.currentRoom.charactorManager.GetCharactor("area_5");
        }

        waitingMove = true;
        //Room.RCAIArea.eventEnterAreaHandler += OnStepGuideMoveEnterArea;

        DataMessageTool.AddHandler(DataMessage.AREA_ENTER, OnStepGuideMoveEnterArea);
        string path = "particles/" + Dict.Blo.DictParticleBlo.GetCommonParticle("zhiyin_dimian").ResourcePath;// "particles/01_general/zhiyin_dimian";
        AssetLoadHelper.Instance.LoadAssetAsync(path, CommonMethod.GetAssetNameFromAssetBundleName(path), typeof(GameObject),
            (obj) =>
        {
            if (obj != null)
            {
                var particleObj = GameObject.Instantiate(obj) as GameObject;
                particleObj.transform.SetParent(areaArrow.transform);
                particleObj.transform.localScale = Vector3.one;
                particleObj.transform.localPosition = Vector3.zero;

                particleObj.SetActive(true);
            }
        });
        
    }

    public void OnStepGuideMoveEnterArea(object areaCharactor)
    {
        string areaId = (areaCharactor as Room.RoomCharactor).name;
        if (waitingMove && ("area_3".Equals(areaId) || "area_5".Equals(areaId)))
        {
            Room.RoomManager.currentRoom.charactorManager.GetCharactor("area_3").transform.DestroyChildren();
            waitingMove = false;
            //Room.RCAIArea.eventEnterAreaHandler -= OnStepGuideMoveEnterArea;
            DataMessageTool.RemoveHandler(DataMessage.AREA_ENTER, OnStepGuideMoveEnterArea);
            NextStep();
        }
    }
    #endregion
    #region GuideLookMonster
    private bool waitingLookMonster = false;
    private void StepGuideLookMonster()
    {
        guideMask.ShowForceWithWord(null,
            curStep.text,
            new Vector3((float)curStep.posX, (float)curStep.posY, 0),
            (GuideMask.DialogType)curStep.dialogType, (GuideMask.HandType)curStep.hand);
        guideMask.ActiveMask(false);
        guideMask.ActiveGray(false);


        waitingLookMonster = true;
        //Room.RCAIArea.eventEnterAreaHandler += OnStepGuideLookMonsterEnterArea;
        DataMessageTool.AddHandler(DataMessage.AREA_ENTER, OnStepGuideLookMonsterEnterArea);

    }

    public void OnStepGuideLookMonsterEnterArea(object areaCharactor)
    {
        string areaId = (areaCharactor as Room.RoomCharactor).name;
        if (waitingLookMonster && areaId.Equals("area_11"))
        {
            //Room.RCAIArea.eventEnterAreaHandler -= OnStepGuideMoveEnterArea;
            DataMessageTool.RemoveHandler(DataMessage.AREA_ENTER, OnStepGuideLookMonsterEnterArea);
            waitingLookMonster = false;

            NextStep();
        }
        
    }
    #endregion
    #region ClickNPC
    private void StepClickNPC()
    {
        guideMask.ShowForceWithWord(null, "", Vector3.zero, 0, 0);
        guideMask.ActiveGray(false);
        StopAllCoroutines();
        StartCoroutine(_StepClickNPC());
    }
    private IEnumerator _StepClickNPC()
    {
        Room.RoomCharactor charactor = null;
        Room.RoomCharactor self = null;
        while(charactor==null||self==null)
        {
            yield return null;
            charactor = Room.RoomManager.currentRoom.charactorManager.GetCharactor(curStep.param);
            self = Room.RoomManager.currentRoom.charactorManager.GetSelfCharactor();
        }
        Room.RoomManager.currentRoom.uiManager.ClickCharactor(curStep.param);
        StartCoroutine(_StepPathFinding(curStep.param));
    }
    #endregion
    #region WaitObject

    private void StepWaitObject()
    {
        guideMask.ShowForceWithWord(null, "", Vector3.zero, 0, GuideMask.HandType.NONE);
        guideMask.ActiveGray(false);
        StopAllCoroutines();
        StartCoroutine(_StepWaitObject());
    }

    private IEnumerator _StepWaitObject()
    {
        GameObject obj = null;
        while (obj == null || obj.activeInHierarchy==false)
        {
            yield return null;
            obj = GameObject.Find(curStep.path);
        }
        NextStep();
    }

    #endregion
    #region WaitPVP
    private bool waitingArenaPage = false;
    private void StepWaitArenaPage()
    {
        waitingArenaPage = true;
        guideMask.ShowForceWithWord(null, "", Vector3.zero, 0, GuideMask.HandType.NONE);
        guideMask.Hide();
    }

    public void StepWaitArenaPageEnd()
    {
        if(waitingArenaPage)
        {
            waitingArenaPage = false;
            NextStep();
        }
    }

    #endregion
    #region WaitRecruit
    private bool waitingRecruit=false;
    private void StepWaitRecruit()
    {
        guideMask.ShowForceWithWord(null, "", Vector3.zero, 0, GuideMask.HandType.NONE);
        guideMask.ActiveGray(false);
        waitingRecruit = true;
    }
    public void StepWaitRecruitEnd()
    {
        if(waitingRecruit)
        {
            waitingRecruit = false;
            NextStep();
        }
    }
    #endregion
    #region FindPlunderItem
    private void StepFindPlunderItem()
    {
        StopAllCoroutines();
        StartCoroutine(_StepFindPlunderItem());
    }
    private IEnumerator _StepFindPlunderItem()
    {
        GameObject btnObject = null;
        while (btnObject == null || btnObject.activeInHierarchy == false)
        {
            btnObject = GameObject.Find(curStep.path);
            yield return null;
        }

        var icon = btnObject.GetComponent<EquipIcon>();
        icon.OnClick();
        NextStep();
    }
    #endregion
    #region Jump
    private void StepJump()
    {
        int offset = int.Parse(curStep.param);
        NextStep(offset);
    }
    #endregion
    #region Wait
    private void StepWait()
    {
        guideMask.ShowForceWithWord(null, "", Vector3.zero, 0, GuideMask.HandType.NONE);
        guideMask.ActiveGray(false);
        StopAllCoroutines();
        StartCoroutine(_StepWait());
    }
    private IEnumerator _StepWait()
    {
        float time = float.Parse(curStep.param);
        yield return new WaitForSeconds(time);
        NextStep();
    }
    #endregion
    #region WaitSelfCreated
    private bool waitingForSelfCreated = false;
    private void StepWaitSelfCreated()
    {
        guideMask.ShowForceWithWord(null, "", Vector3.zero, 0, 0);
        guideMask.ActiveGray(false);
        StopAllCoroutines();
        waitingForSelfCreated = true;
        DataMessageTool.AddHandler(DataMessage.ROOM_SELF_CREATED, OnTownSelfCreated);
    }

    public void OnTownSelfCreated(object room)
    {
        if(waitingForSelfCreated)
        {
            waitingForSelfCreated = false;
            DataMessageTool.RemoveHandler(DataMessage.ROOM_SELF_CREATED, OnTownSelfCreated);
            NextStep();
        }
    }
    #endregion
    #region Transfer
    private void StepTransfer()
    {
        guideMask.ShowForceWithWord(null, "", Vector3.zero, 0, 0);
        guideMask.ActiveGray(false);
        var pos = GetPosition(curStep.param);
        StartCoroutine(StartMove(pos));
    }
    IEnumerator StartMove(Vector3 pos)
    {
        while((RoomManager.currentRoom as RoomTown)==null
            || (RoomManager.currentRoom.charactorManager.GetSelfCharactor()==null))
        {
            yield return null;
        }

        GameObject guangCopy;
        GameObject whitePanel = Instantiate(Resources.Load("prefab/WhitePanel")) as GameObject;
        whitePanel.transform.parent = GameObject.Find("/UI Root").transform;
        whitePanel.transform.localPosition = Vector3.zero;
        whitePanel.transform.localScale = Vector3.one;
        string csz1eff = "particles/" + Dict.Blo.DictParticleBlo.GetCommonParticle("Chuansongzhen1").ResourcePath;
        yield return StartCoroutine(AssetLoad.AssetBundleManager.Instance.LoadAssetBundleCoroutine(csz1eff));
        Object oj0 = AssetLoad.AssetBundleManager.Instance.GetAssetFromBundle(csz1eff, CommonMethod.GetAssetNameFromAssetBundleName(csz1eff), typeof(GameObject));
        guangCopy = GameObject.Instantiate(oj0) as GameObject;

        GameObject copyPos = new GameObject();

        var self = Room.RoomManager.currentRoom.charactorManager.GetSelfCharactor();
        copyPos.transform.position = self.transform.position;
        self.gameObject.SetActive(false);
        if ((self.ui as RCUIPlayer).Name.title.isActiveAndEnabled)
            (self.ui as RCUIPlayer).Name.title.gameObject.SetActive(false);

        guangCopy.transform.SetParent(copyPos.transform);

        guangCopy.transform.localPosition = Vector3.zero;

        yield return new WaitForSeconds(1.3f);
        //if (guangCopy != null) Destroy(guangCopy);
        //白屏
        Transform whiteMask = whitePanel.transform.Find("WhiteMask");
        UITweener tweener = whiteMask.GetComponent<UITweener>();
        tweener.ResetToBeginning();
        tweener.PlayForward();


        yield return new WaitForSeconds(1.0f);
        if (guangCopy != null) Destroy(guangCopy);
        ////服务器交互


        //创建空GameObject //播放传送完成动画
        GameObject emptyObject = new GameObject();

        emptyObject.transform.position = new Vector3(pos.x, pos.y - 0.7f, pos.z);
        string csz2Eff = "particles/" + Dict.Blo.DictParticleBlo.GetCommonParticle("Chuansongzhen2").ResourcePath;
        yield return StartCoroutine(AssetLoad.AssetBundleManager.Instance.LoadAssetBundleCoroutine(csz2Eff));
        Object oj = AssetLoad.AssetBundleManager.Instance.GetAssetFromBundle(csz2Eff,CommonMethod.GetAssetNameFromAssetBundleName(csz2Eff), typeof(GameObject));
        guangCopy = Instantiate(oj) as GameObject;
        guangCopy.transform.SetParent(emptyObject.transform);
        guangCopy.transform.localPosition = Vector3.zero;
        guangCopy.transform.localScale = Vector3.one;
        //guangCopy.transform.localEulerAngles = Vector3.zero;
        guangCopy.transform.localEulerAngles = new Vector3(0, 0, 0);

        var town = Room.RoomManager.currentRoom as Room.RoomTown;
        
        //town.netManager.TransferScene( ServerScene.Town, pos, () =>
        //{
            
        //});

        ManagerController.Instance.TrySceneTransfer(ServerScene.Town, pos, null, () => 
        {
            town.netManager.SendCSCurrentPosition(null);
        });


        //self.gameObject.SetActive(false);
        TouchKit.SetEnabled(false);

        var texture = whiteMask.GetComponent<UITexture>();
        //StartCoroutine(alphaChange(texture));
        yield return new WaitForSeconds(0.5f);

        texture.alpha = 0f;

        yield return new WaitForSeconds(1.0f);
        //角色出现 可以移动
        Destroy(whitePanel);
        TouchKit.SetEnabled(true);
        yield return new WaitForSeconds(1.4f);
        if (guangCopy != null) Destroy(guangCopy);
        if (emptyObject != null) Destroy(emptyObject);
        if (copyPos != null) Destroy(copyPos);

        NextStep();
    }
    #endregion
    #region Move
    private void StepMove()
    {
        guideMask.ShowForceWithWord(null, "", Vector3.zero, 0, 0);
        var self = RoomManager.currentRoom.charactorManager.GetSelfCharactor();
        var selfAI = self.ai as RCAISelf;
        selfAI.AutoGoto(GetPosition(curStep.param), null);
        NextStep();
    }
    #endregion
    #region GuideFish
    private void StepGuideFish()
    {
        guideMask.ShowForceWithWord(null, "", Vector3.zero, 0, 0);
        guideMask.ActiveGray(false);
        OnGuideFishSelfCreated(null);
        DataMessageTool.AddHandler(DataMessage.ROOM_SELF_CREATED, OnGuideFishSelfCreated);
    }
    private void OnGuideFishSelfCreated(object o)
    {
        var field = RoomManager.currentRoom as RoomField;
        field.charactorManager.CreateResourceGuide("group_fish_001", "fish_pos_0");
        var self = field.charactorManager.GetSelfCharactor();
        var selfAI = self.ai as RCAISelf;
        selfAI.AutoGoto(new Vector3(7, -0.5f, 17), () =>
        {
            DataMessageTool.RemoveHandler(DataMessage.ROOM_SELF_CREATED, OnGuideFishSelfCreated);
            NextStep();
        });
    }
    #endregion
    #region GuideMine
    private void StepGuideMine()
    {
        guideMask.ShowForceWithWord(null, "", Vector3.zero, 0, 0);
        guideMask.ActiveGray(false);
        OnGuideMineSelfCreated(null);
        DataMessageTool.AddHandler(DataMessage.ROOM_SELF_CREATED, OnGuideMineSelfCreated);
    }
    private void OnGuideMineSelfCreated(object o)
    {
        var field = RoomManager.currentRoom as RoomField;
        field.charactorManager.CreateResourceGuide("group_mine_001", "mine_pos_0");
        var self = field.charactorManager.GetSelfCharactor();
        var selfAI = self.ai as RCAISelf;
        selfAI.AutoGoto(new Vector3(20.84f,-0.45f,7.61f), () =>
        {
            DataMessageTool.RemoveHandler(DataMessage.ROOM_SELF_CREATED, OnGuideMineSelfCreated);
            NextStep();
        });
    }
    #endregion
    #region RotateHero
    private void StepRotateHero()
    {
        guideMask.ShowForceWithWord(null,
            curStep.text,
            new Vector3((float)curStep.posX, (float)curStep.posY, 0),
            (GuideMask.DialogType)curStep.dialogType, (GuideMask.HandType)curStep.hand);
        guideMask.ActiveGray(false);

        var heroAni = GameObject.Find(curStep.path);
        if(heroAni!=null)
        {
            var tweenAction = gameObject.AddMissingComponent<TweenAction>();
            var rotate = new TweenActionRotate(heroAni.transform, new Vector3(0, -360, 0), 2, false);
            tweenAction.RunAction(rotate);
        }
        StartCoroutine(_StepRotateHero());
    }
    private IEnumerator _StepRotateHero()
    {
        yield return new WaitForSeconds(2f);
        guideMask.onClickCallback = StepRotateHeroEnd;

    }
    private void StepRotateHeroEnd()
    {
        guideMask.onClickCallback = null;
        NextStep();
    }
    #endregion
    #region ShowWindow
    private void SetShowWindowState()
    {
        TownPage page = PageManager.instance.currentPage as TownPage;
        if (page != null)
            page.showState = true;        
        NextStep();
    }
    #endregion
    #endregion


    #region Help

    private void RemoveGuideDelegate(List<EventDelegate> list)
    {
        for (int i = 0; i < list.Count;)
        {
            if(list[i].target==this)
            {
                list.RemoveAt(i);
            }
            else
            {
                i++;
            }
        }
    }
    public List<EventDelegate> GetEventDelegatesOfObj(GameObject obj)
    {
        if (obj == null)
        {
            Debug.Log("####[GuideMessage]NotFoundButton####");
        }
        List<EventDelegate> list = null;
        var uiButton = obj.GetComponent<UIButton>();
        if (uiButton != null)
        {
            list=uiButton.onClick;
        }
        var uiImageButton = obj.GetComponent<UIImageButton>();
        if (uiImageButton != null)
        {
            list = uiImageButton.onClick;
        }
        var uiEventTrigger = obj.GetComponent<UIEventTrigger>();
        if (uiEventTrigger != null)
        {
            list = uiEventTrigger.onClick;
        }

        return list;
    }
    
    private TableGuide GetCurGuide()
    {
        return Dict.DictDataManager.Instance.tableGuideDao.GetById(curGuideId);
    }
    #endregion
    #region Trigger
    public void OnLevelUp()
    {
        var curGuide = GetCurGuide();
        if (curGuide == null)
            return;
        foreach (var tmp in Dict.DictDataManager.Instance.tableGuideDao.CacheList)
        {
            if (tmp.levelTrigger == StaticData.playerData.level)
            {
                GuideStart(tmp.guideId, tmp.levelTag);
                return;
            }
        }
    }
    public void OnQuestComplete(string completeQuestId)
    {
        var curGuide = GetCurGuide();
        if (curGuide == null)
            return;
        foreach (var tmp in Dict.DictDataManager.Instance.tableGuideDao.CacheList)
        {
            if (tmp.order <= curGuide.order || string.IsNullOrEmpty(tmp.questTrigger))
                continue;
            if(completeQuestId.Equals(tmp.questTrigger))
            {
                GuideStart(tmp.guideId, tmp.questTag);
                break;
            }
        }
    }
    private void OnGuideEnd()
    {
        running = false;  

        StaticData.playerData.currentGuideId = curGuideId;
        var curGuide = GetCurGuide();
        if (!string.IsNullOrEmpty(curGuide.endGuide))
        {
            GuideStart(curGuide.endGuide, curGuide.endTag);
        }
        else
        {
            guideMask.gameObject.SetActive(false);
        }
    }
    public void OnLogin(bool town)
    {
        
        curGuideId = StaticData.playerData.currentGuideId;
        var curGuide = GetCurGuide();

        if (curGuide == null)
            return;

        Debug.Log("####[GuideMessage]Login:" + curGuide.guideId + "(" + curGuide.order + ")####");

        if(!string.IsNullOrEmpty(curGuide.loginGuide))
        {
            if (town)
            {
                GuideStart(curGuide.loginGuide, curGuide.loginTag);
            }
            else
            {
                GuideStart(curGuide.loginGuide, curGuide.loginTag2);
            }
            return;
        }

        //int playerLevel = StaticData.playerData.level;
        foreach (var tmp in Dict.DictDataManager.Instance.tableGuideDao.CacheList)
        {
            if (tmp.order <= curGuide.order || tmp.levelTrigger == 0)
                continue;
            if (tmp.levelTrigger==StaticData.playerData.level)
            {
                if(town)
                {
                    GuideStart(tmp.guideId, tmp.levelTag);
                }
                else
                {
                    GuideStart(tmp.guideId, tmp.levelTag2);
                }
                return;
            }
        }
    }
    public void OnChooseRole()
    {
        GuideStart("guide_choose_role", "start");
    }
    public void OnCookRoomOpen()
    {
        if(PlayerPrefs.HasKey("guide_cook_room"))
        {
            int param = PlayerPrefs.GetInt("guide_cook_room");
            if(param==1)
            {
                //PlayerPrefs.SetInt("guide_cook_room", 0);
                return;
            }
        }

        PlayerPrefs.SetInt("guide_cook_room", 1);
        GuideStart("guide_cook_room","start");
    }
    public void OnSmeltRoomOpen()
    {
        if (PlayerPrefs.HasKey("guide_smelt_room"))
        {
            int param = PlayerPrefs.GetInt("guide_smelt_room");
            if (param == 1)
            {
                //PlayerPrefs.SetInt("guide_smelt_room", 0);
                return;
            }
        }

        PlayerPrefs.SetInt("guide_smelt_room", 1);
        GuideStart("guide_smelt_room", "start");
    }
    #endregion


    #region Help
    public string GetRunningGuide()
    {
        if (running)
        {
            return curGuideId;
        }
        else
        {
            return string.Empty;
        }
    }
    public int GetGuideOrder()
    {
        var curGuide = GetCurGuide();
        if (curGuide == null||curGuide.order<0)
        {
            return 99;
        }
        return curGuide.order;
    }
    public void Clear()
    {
        guideMask.gameObject.SetActive(false);
        running = false;
        this.waitingArenaPage = false;
        this.waitingForSelfCreated = false;
        this.waitingLookMonster = false;
        this.waitingMove = false;
        this.waitingRecruit = false;
        this.waitingStepId = null;
        this.curGuideId = "";
        this.curStep = null;
        this.curStepIdx = 0;
        
    }
    private bool CheckGuideCanStart(string guideId)
    {
        if (guideId.Equals("guide_plunder")|| guideId.Equals("guide_plunder_pvp"))
        {
            var frag1 = StaticData.playerData.treasureFrag.GetFrag("frag_trea_001_1");
            var frag2 = StaticData.playerData.treasureFrag.GetFrag("frag_trea_001_2");
            var frag3 = StaticData.playerData.treasureFrag.GetFrag("frag_trea_001_3");
            if (frag1.num > 0 && frag2.num > 0 && frag3.num == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        return true;
    }

    public Vector3 GetPosition(string str)
    {
        if (str.Equals("selfPos"))
        {
            return Room.RoomManager.currentRoom.charactorManager.GetSelfCharactor().transform.position;
        }
        var splits = str.Split(',');
        Vector3 v;
        v.x = float.Parse(splits[0]);
        v.y = float.Parse(splits[1]);
        v.z = float.Parse(splits[2]);
        return v;
    }
    
    public string GetGuideOfLevel(int level)
    {
        var curGuide = GetCurGuide();
        if (curGuide == null)
            return "";
        foreach (var tmp in Dict.DictDataManager.Instance.tableGuideDao.CacheList)
        {
            if (tmp.levelTrigger == StaticData.playerData.level)
            {
                return tmp.guideId;
            }
        }
        return "";
    }
    #endregion
}